package com.lyl.xxx.modules.web.montior.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.lyl.xxx.common.constants.RedisConstant;
import com.lyl.xxx.common.utils.RedisUtil;
import com.lyl.xxx.modules.framework.security.model.details.LoginDetails;
import com.lyl.xxx.modules.web.montior.model.dto.OnlineUserDTO;
import com.lyl.xxx.modules.web.montior.model.vo.OnlineUserVO;
import com.lyl.xxx.modules.web.montior.service.OnlineService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class OnlineServiceImpl implements OnlineService {

    @Override
    public PageInfo<OnlineUserVO> getOnlineUserList(Integer pageNo, Integer pageSize, OnlineUserDTO dto) {
        //1. 获取全部的在线登录key
        Set<String> keys = RedisUtil.keys(RedisConstant.LOGIN_TOKEN + "*");
        //2. 从redis中获取出对应的数据
        List<OnlineUserVO> voList = RedisUtil.mGet(keys).stream()
                .map(o -> JSONUtil.toBean(JSONUtil.toJsonStr(o), LoginDetails.class))
                .map(o -> {
                    OnlineUserVO onlineUserVO = BeanUtil.copyProperties(o, OnlineUserVO.class);
                    return onlineUserVO.setUserName(o.getUsername())
                            .setLoginIp(o.getSysUser().getLoginIp())
                            .setLoginTime(o.getSysUser().getLoginDate())
                            .setTokenId(o.getToken());
                })
                .filter(t -> CharSequenceUtil.isBlank(dto.getLoginAddress()) || CharSequenceUtil.emptyIfNull(t.getLoginAddress()).contains(dto.getLoginAddress()))
                .filter(t -> CharSequenceUtil.isBlank(dto.getUserName()) || CharSequenceUtil.emptyIfNull(t.getUserName()).contains(dto.getUserName()))
                .collect(Collectors.toList());
        final long total = voList.size();
        //3. 根据分页条件对结果进行分页
        voList = ListUtil.page(pageNo - 1, pageSize, voList);
        //4. 转换成对应的vo,并组装称分页列表返回
        PageInfo<OnlineUserVO> pageInfo = PageInfo.of(voList);
        pageInfo.setPageNum(pageNo);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        return pageInfo;
    }

    @Override
    public boolean forceLogout(String tokenId) {
        RedisUtil.del(RedisConstant.LOGIN_TOKEN + tokenId);
        // 记录强退日志
        return true;
    }
}
